package com.xl.utils.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author xionglin
 * @Classname FileMD5
 * @Description 对比两个文件是不是同一文件
 * @Date 2019/5/13 14:23
 */
public class FileMD5Util {
    /**
     * 私有化构成器避免工具类被实例化
     */
    private FileMD5Util(){};



    private static String getFileMD5String(File file){
        MessageDigest mMessageDigest = null;
        try {
            mMessageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        try {
            InputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) > 0) {
                mMessageDigest.update(buffer, 0, length);
            }
            fis.close();
            return new BigInteger(1, mMessageDigest.digest()).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




    /**
     * @Description: 判断文件1和文件2是否是同一文件
     * @Param: 文件1的路径
     * @Param: 文件2的路径
     * @return:  相同返回true，否则返回false
     * @Author: xionglin
     * @Date: 2019/5/13 14:40
     */
    public static boolean isSameFile(String filePath1, String filePath2) {
        boolean result = true;
        File file1 = new File(filePath1);
        File file2 = new File (filePath2);

        if (file1.length() != file2.length()) {
            result = false;
        } else {
            String file1MD5 = getFileMD5String(file1);
            String file2MD5 = getFileMD5String(file2);
            if(file1MD5 == null || file2MD5 == null){
                result = false;
            }
            if (!file1MD5.equals(file2MD5)) {
                result = false;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(isSameFile("C:\\Users\\ASUS\\Pictures\\Saved Pictures\\img.jpg","C:\\Users\\ASUS\\Pictures\\Saved Pictures\\img.jpg"));
    }
}
